import urlConfig from '@/common/config.js'

const request = {}
const headers = {}

request.globalRequest = (url, method, data, power, isheader=false) => {
	
	switch (power) {
		case 1:
			headers['Content-Type'] = 'application/json;charset=UTF-8'
			break;
		case 2:
			headers['accesstoken'] = uni.getStorageSync('userinfo').token
			break;
		case 3:
			responseType = 'blob'
			break;
		default:
			headers['Content-Type'] = 'application/json;charset=UTF-8'
			headers['Authorization'] = `Bearer ${uni.getStorageSync('token')}`
			break;
	}
	
	let promise = new Promise(function(resolve, reject) {
	    uni.request({
			url: urlConfig.url_config + url,
			method,
			data: data,
			dataType: 'json',
			header: headers
		}).then(
	        (res) => {
				if(res[1].data.code==301){
					// 需重新登录 跳转登录页
					uni.clearStorageSync();
					uni.reLaunch({
						url:'/pages/login/login'
					})
				}else{
					if(isheader){
						resolve(res[1])
					}else{
						resolve(res[1].data)
					}
				}
	        }
	    ).catch(
	        (response) => {
				uni.showToast({
					icon:"none",
					title:'请求失败'
				})
				console.log(response)
	            reject(response)
	        }
	    )
	})
	return promise
}

export default request
